//
//  ReduceViewController.swift
//  XiaoXiangMu1604
//
//  Created by qianfeng on 16/9/26.
//  Copyright © 2016年 SunPiaoLiang. All rights reserved.
//

import UIKit

/*
降价界面
*/

class ReduceViewController: LFBaseViewController {

    private var cateId: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //添加分页功能
        addRefresh()
        
        createMyNav()
        
        downloadData()
        
    }
    //导航
    func createMyNav(){
        
        addNavButton("分类", target: self, action: "gotocategory", isLeft: true)
        
        addNavTitle("降价")
        
        addNavButton("设置", target: self, action: "gotoSetPage", isLeft: false)
        
    }
    //分类
    func gotocategory(){
        
        let cateCtl = CategoryViewController()
        
        //类型
        cateCtl.type = .Reduce
        
        cateCtl.delegate = self
        
        //隐藏tabbar
        hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(cateCtl, animated: true)
        
        hidesBottomBarWhenPushed = false
        
    }
    func gotoSetPage(){
        
        
        let setCtl = SettingViewController()
        
        hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(setCtl, animated: true)
        
        hidesBottomBarWhenPushed = false

        
    }
    override func downloadData(){
        
        ProgressHUD.showOnView(view)
        
        var urlString = String(format: kReduceUrl, curPage)
        
        if cateId != nil{
            
            urlString = urlString.stringByAppendingString("&category_id=\(cateId!)")
            
        }
        
        let d = LFDownloader()
        
        d.delegate = self
        
        d.downloadWithURLString(urlString)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
//MARK:LFDownloader的代理
extension ReduceViewController:LFDownloaderDelegate{
    
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        
        ProgressHUD.hideAfterFailOnView(self.view)
    }
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        //下拉刷新需要清空数据源
        if curPage == 1{
            
            dataArray.removeAllObjects()
            
        }
        
        let result = try!NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        
        if result.isKindOfClass(NSDictionary){
            
            let dict = result as! Dictionary<String,AnyObject>
            
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
            
            for appDict in array{
                
                let model = LimitModel()
                
                model.setValuesForKeysWithDictionary(appDict)
                
                dataArray.addObject(model)
                
            }
            
            dispatch_async(dispatch_get_main_queue(), {
                
                self.tbView?.reloadData()
                
                self.tbView?.headerView?.endRefreshing()
                
                self.tbView?.footerView?.endRefreshing()
                
                ProgressHUD.hideAfterSuccessOnView(self.view)
                
                
            })
            
        }
        
    }

}
//MARK:UITabelView的代理
extension ReduceViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 100
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellId = "reducecellId"
        
        var cell = tbView?.dequeueReusableCellWithIdentifier(cellId) as? ReduceCell
        
        if cell == nil{
            
            cell = NSBundle.mainBundle().loadNibNamed("ReduceCell", owner: nil, options: nil).last as? ReduceCell
            
        }
        //显示数据
        let model = dataArray[indexPath.row] as! LimitModel
        
        cell?.config(model, atIndex:indexPath.row+1)
        
        return cell!
        
        
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        //点击跳转详情界面
        let model = dataArray[indexPath.row] as! LimitModel
        
        let detailCtl = DetailViewController()
        
        detailCtl.appId = model.applicationId
        
        hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(detailCtl, animated: true)
        
        hidesBottomBarWhenPushed = false
        
    }

}
//MARK:CategoryViewController的代理
extension ReduceViewController:CategoryViewControllerDelegate{
    
    func didClickCate(cateId: String, cateName: String) {
        
        var titleStr = "降价一" + cateName
        
        if cateName == "全部"{
         
            titleStr = "降价"
            
        }
        addNavTitle(titleStr)
        
        self.cateId = cateId
        
        curPage = 1
        
        downloadData()
        
    }
    
    
}